<?php

use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Query\Builder;
use app\modules\Admin\models\orderModel;
use Illuminate\Database\Capsule\Manager as DB;

#[店铺收益]
class DianpuprofitController extends McommonController
{
    public function init() {
        parent::init();
        $this->model = (new orderModel())->newQueryWithoutScope('dianpu_id')->where('dianpu_id', $this->auth->dianpu_id);
        $this->table = 'order';
        $this->primaryKey = 'id';
    }

    #[店铺收益列表]
    public function indexAction($returnData = FALSE)
    {
        if($this->isPost()) {
            $this->model = $this->model->with([
                'orderItems' => function (HasMany $query) {
                    $query->where('refund_status', '<', 1);
                    $query->select(['id', 'order_id', 'goods_id', 'goods_title', 'goods_image', 'goods_price', 'pay_price', 'cost_price', 'goods_num', 'goods_sku_text']);
                    $query->withSum('tuikereward', 'commission');
                    $query->withSum('agentreward', 'commission');
                }
            ])->select(['id', 'order_sn', 'pay_type', 'pay_fee', 'paytime', 'created_at']);
            $post_data = $this->postData;
            if(isset($post_data['mode']) &&  !empty($post_data['mode'])){
                switch ($post_data['mode']){
                    case 'paid':
                        array_push($this->search, ['status', '=', 1]);
                        break;
                    case 'finished':
                        array_push($this->search, ['status', '=', 2]);
                        break;
                    default:
                        array_push($this->search, ['status', '>', 0]);
                }
            }
            if(isset($post_data['start_on']) && !empty($post_data['start_on'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['start_on']);
            }
            if(isset($post_data['end_on']) && !empty($post_data['end_on'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['end_on']);
            }
            $keywordsTypeArray = [
                'order_id' => 'order_id',
                'order_sn' => 'order_sn',
                'user_id' => 'user_id',
                'user_phone' => 'user_phone',
                'customer_id' => 'customer_id',
                'goods_id' => 'goods_id',
                'goods_name' => 'goods_name',
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['order_id'] && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['order_sn']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->search, ['order_sn', 'like', "%{$post_data['keywords']}%"]);
                    }
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['member_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['customer_id'] && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['customer_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['goods_id'] && intval($post_data['keywords']) > 0){
                    $order_ids = \app\modules\Admin\models\orderItemModel::query()->where('goods_id', $post_data['keywords'])->pluck('order_id')->toArray();
                    array_push($this->condition_in, ['id', $order_ids]);
                    unset($order_ids);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['goods_name'] && intval($post_data['keywords']) > 0){
                    $order_ids = \app\modules\Admin\models\orderItemModel::query()->where('goods_title', 'like', "%{$post_data['keywords']}%")->pluck('order_id')->toArray();
                    array_push($this->condition_in, ['id', $order_ids]);
                    unset($order_ids);
                }
            }
            unset($keywordsTypeArray);
            $datas = parent::indexAction(true);
            if(is_array($datas) && isset($datas['rows']) && count($datas['rows'])){
                foreach ($datas['rows'] as &$row){
                    if (isset($row['order_items']) && is_array($row['order_items']) && count($row['order_items'])){
                        foreach ($row['order_items'] as &$item){
                            if(empty($item['tuikereward_sum_commission'])){
                                $item['tuikereward_sum_commission'] = 0.00;
                            }
                            if(empty($item['agentreward_sum_commission'])){
                                $item['agentreward_sum_commission'] = 0.00;
                            }
                            if(empty($item['cost_price'])){
                                $item['cost_price'] = 0.00;
                            }
                            if(empty($item['pay_price'])){
                                $item['pay_price'] = 0.00;
                            }
                            $item['platform_cut'] = 0.00;
                            $platform_cut_ratio = configModel::query()->where('type', 29)->where('key', 'merchant_platform_cut_ratio')->value('value');
                            if(!empty($platform_cut_ratio) && $item['pay_price'] > 0){
                                $platform_cut_ratio_percentage = bcdiv($platform_cut_ratio, 100, 2);
                                $item['platform_cut'] = bcmul($item['pay_price'], $platform_cut_ratio_percentage, 2);
                            }
                            $platform_profit = bcsub($item['pay_price'], $item['platform_cut'], 3);
                            $platform_profit = bcsub($platform_profit, $item['qudaireward_sum_commission'], 3);
                            $platform_profit = bcsub($platform_profit, $item['tuikereward_sum_commission'], 3);
                            $item['dianpu_money'] = round($platform_profit ,2);
                            $item['cost_price'] = $item['cost_price'] * $item['goods_num'];
                            $platform_profit = bcsub($platform_profit, $item['cost_price'], 3);
                            $item['dianpu_profit'] = round($platform_profit ,2);
                        }
                    }

                }
            }
            json($datas);
        }else{
            $this->_view->display( strtolower($this->controller) . '/index.html');
        }


    }

//    #[平台收益导出]
//    public function exportAction()
//    {
//        $type     = $this->get('keywordsType');
//        $keywords = $this->get('keywords');
//        $startOn = $this->get('start_on');
//        $endOn = $this->get('end_on');
//        $mode = $this->get('mode');
//
//        $dirpath = APP_PATH . '/public/excel/';
//        if ($dirpath !== '.' && !file_exists($dirpath)) {
//            mkdir($dirpath, 0777, true);
//        }
//        $filename = 'PlatformProfit' . date('Ymd') . uniqid() . '.xlsx';
//        $filepath = $dirpath . $filename;
//        $res = exec("php ". APP_PATH . "/public/cli.php export/platformprofit \"mode={$mode}&type={$type}&keywords={$keywords}&start_on={$startOn}&end_on={$endOn}&path={$filepath}\"");
//        if ($res === 'Done' && file_exists($dirpath . $filename)) {
//            if( $webpath = syncFile($filepath) ){
//                ret(0, '平台收益记录导出excel成功', $webpath);
//            }
//        }
//        ret(30003, '平台收益记录导出失败');
//    }
}